package com.gitee.empty_null.starter.configuration;

import com.gitee.empty_null.authorization.configurer.OAuth2AuthenticationProviderConfigurer;
import com.gitee.empty_null.authorization.converter.OAuth2AuthenticationConverterManager;
import com.gitee.empty_null.authorization.customizer.OAuth2ResourceServerConfigurerCustomizer;
import com.gitee.empty_null.authorization.handler.OAuth2AuthenticationFailureHandler;
import com.gitee.empty_null.authorization.handler.OAuth2AuthenticationSuccessHandler;
import com.gitee.empty_null.authorization.handler.OidcClientRegistrationResponseHandler;
import com.gitee.empty_null.authorization.provider.OAuth2AuthenticationProviderManager;
import com.gitee.empty_null.constants.DefaultConstants;
import com.gitee.empty_null.orm.repository.FlexRegisteredClientRepository;
import com.gitee.empty_null.orm.service.IRegisteredClientService;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xuhainan
 * @date 2024/1/16 10:02
 * @region hefei
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(
            HttpSecurity httpSecurity,
            UserDetailsService userDetailsService,
            PasswordEncoder passwordEncoder,
            OAuth2ResourceServerConfigurerCustomizer oAuth2ResourceServerConfigurerCustomizer
    ) throws Exception {
        OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();
        httpSecurity.apply(authorizationServerConfigurer);

        // OAuth2AuthorizationServerConfigurer
        OAuth2AuthenticationFailureHandler failureHandler = new OAuth2AuthenticationFailureHandler();

        authorizationServerConfigurer.clientAuthentication(endpoint -> endpoint.errorResponseHandler(failureHandler));

        authorizationServerConfigurer.authorizationEndpoint(endpoint -> {
            endpoint.errorResponseHandler(failureHandler);
            endpoint.consentPage(DefaultConstants.AUTHORIZATION_CONSENT_URI);
        });

        // tokenEndpoint Configuration
        authorizationServerConfigurer.tokenEndpoint(endpoint -> {
            // 自定义Provider类型
            endpoint.authenticationProviders(consumer -> {
                List<AuthenticationProvider> providers =
                        OAuth2AuthenticationProviderManager.createAuthenticationProviders(httpSecurity, userDetailsService);
                consumer.addAll(providers);
            });
            // 自定义Converter类型
            endpoint.accessTokenRequestConverters(consumer -> {
                List<AuthenticationConverter> converters = OAuth2AuthenticationConverterManager.createAuthenticationConverters();
                consumer.addAll(converters);
            });
            endpoint.errorResponseHandler(failureHandler);
            endpoint.accessTokenResponseHandler(new OAuth2AuthenticationSuccessHandler());
        });
        authorizationServerConfigurer.tokenIntrospectionEndpoint(endpoint -> endpoint.errorResponseHandler(failureHandler));
        authorizationServerConfigurer.tokenRevocationEndpoint(endpoint -> endpoint.errorResponseHandler(failureHandler));

        // oidc
        authorizationServerConfigurer.oidc(oidc ->
                oidc.clientRegistrationEndpoint(endpoint -> {
                    endpoint.errorResponseHandler(failureHandler);
                    endpoint.clientRegistrationResponseHandler(new OidcClientRegistrationResponseHandler());
                })
        );

        RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();
        // 仅拦截 OAuth2 Authorization Server 的相关 endpoint
        httpSecurity.securityMatcher(endpointsMatcher)
                .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests.anyRequest().authenticated())
                .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher))
                .oauth2ResourceServer(oAuth2ResourceServerConfigurerCustomizer)
                .exceptionHandling(exceptions ->
                        exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
                )
                .apply(new OAuth2AuthenticationProviderConfigurer(passwordEncoder, userDetailsService))
        ;

        return httpSecurity.build();
    }


    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails userDetails = User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(userDetails);
    }

//    @Bean
//    public RegisteredClientRepository registeredClientRepository() {
//        RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
//                .clientId("client")
//                .clientSecret("{noop}secret")
//                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
//                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
//                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
//                .authorizationGrantType(AuthorizationGrantType.PASSWORD)
//                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
//                .redirectUri("http://localhost:9000/demo/receiver")
//                .postLogoutRedirectUri("http://127.0.0.1:9000/")
//                .scope(OidcScopes.OPENID)
//                .scope(OidcScopes.PROFILE)
//                .scope(OidcScopes.PHONE)
//                .clientSettings(ClientSettings.builder()
//                        .requireAuthorizationConsent(true).build())
//                .tokenSettings(TokenSettings.builder()
//                        .accessTokenTimeToLive(Duration.ofMinutes(1))
//                        .build())
//                .build();
//        return new InMemoryRegisteredClientRepository(oidcClient);
//    }

    @Bean
    public RegisteredClientRepository registeredClientRepository(IRegisteredClientService registeredClientService,
                                                                 PasswordEncoder passwordEncoder) {
        return new FlexRegisteredClientRepository(registeredClientService, passwordEncoder);
    }

    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID("ynby_platform_2021")
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> jwtTokenCustomizer() {
        return context -> {
            if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
                Authentication principal = context.getPrincipal();
//                User user = (User) principal.getPrincipal();
                context.getClaims().claims(claims -> {
                    Set<String> roles = AuthorityUtils.authorityListToSet(principal.getAuthorities())
                            .stream()
                            .map(c -> c.replaceFirst("^ROLE_", ""))
                            .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
                    claims.put("roles", roles);
//                    claims.put("user", user.getUsername());
                });
            }
        };
    }

    @Bean
    public OAuth2ResourceServerConfigurerCustomizer oAuth2ResourceServerConfigurerCustomizer(JwtDecoder jwtDecoder) {
        return new OAuth2ResourceServerConfigurerCustomizer(jwtDecoder);
    }

    @Bean
    public AuthorizationServerSettings authorizationServerSettings() {
        return AuthorizationServerSettings.builder().build();
    }


}
